<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="auto"
      size="small"
      class="ry_form">
      <el-form-item label="物资名称" prop="materialName">
        <el-input size="small" v-model="queryParams.materialName" placeholder="请输入物资名称"/>
      </el-form-item>
      <el-form-item label="日期" prop="Time">
        <el-date-picker
          v-model="queryParams.Time"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          size="small"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          @change="handleChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="flex_one tr">
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div :style="{ marginBottom: '10px', textAlign: 'right' }">
      <el-button type="primary" icon="el-icon-edit" size="small" @click="showAddForm">新建消耗记录</el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="orderList"
      cell-class-name="my-cell">
      <el-table-column label="序号" type="index" :index="index => index + 1" />
      <el-table-column prop="id" label="物资ID" />
      <el-table-column prop="materialName" label="物资名称" />
      <el-table-column prop="consumptionQuantity" label="消耗量" />
      <el-table-column prop="imageUrl" label="图片">
        <template slot-scope="scope">
          <img :src="scope.row.imageUrl" style="width: 100px; height: 100px; object-fit: cover;" />
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="small-padding fixed-width" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDetail(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <InBody v-show="total>0">
      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </InBody>
    <el-dialog title="配置" :visible.sync="dialogVisible" width="600px" @close="closeAddForm">
      <el-form
        :model="addForm"
        :rules="rules"
        label-position="right"
        label-width="100px"
        ref="addForm"
        :disabled="editDisabled">
        <el-form-item label="物资" prop="materialId">
          <el-select v-model="addForm.materialId" filterable placeholder="请选择">
            <el-option
              v-for="item in materialList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消耗日期" prop="consumptionDate">
          <el-date-picker
            v-model="addForm.consumptionDate"
            type="date"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="当前库存">
          <span>{{material.remainingQuantity || '--'}}</span>
        </el-form-item>
        <el-form-item label="消耗量" prop="consumptionQuantity">
          <el-input-number v-model="addForm.consumptionQuantity" :min="1" :step="1" />
        </el-form-item>
        <el-form-item label="上传截图" prop="imageUrl">
          <el-upload
            class="file-uploader"
            :action="`${baseUrl}/file/upload`"
            :show-file-list="false"
            accept=".png,.jpg,.jpeg"
            :on-success="handleFileSuccess">
            <img v-if="addForm.imageUrl" :src="addForm.imageUrl" class="file" />
            <i v-else class="el-icon-plus file-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddForm">取消</el-button>
        <el-button type="primary" v-if="!editDisabled" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dateUtil from '@/utils/DateUtil';
import { mapGetters } from "vuex";
import { queryMaterialList } from "@/api/purchase";
import { createConsume, queryStockList } from "@/api/inventory";
import { omit, pick } from 'lodash'
import { getBaseUrl } from "@/utils";

export default {
  computed: {
    ...mapGetters(['userId', 'name']),
    material() {
      return this.materialList.find(v => v.id === this.addForm.materialId) || {}
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      baseUrl: getBaseUrl(),
      // 时间配置
      pickerOptions: {
        shortcuts: dateUtil.getTimeShort2()
      },
      materialList: [],
      ids: [],
      // 总条数
      total: 0,
      // 订单表表格数据
      orderList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: null,
        Time: []
      },
      dialogVisible: false,
      editDisabled: false,
      addForm: {
        materialId: '',
        consumptionDate: '',
        imageUrl: '',
        consumptionQuantity: ''
      },
      rules: {
        materialId: [{ required: true, message: '请选择物资', trigger: 'blur' }],
        consumptionDate: [{ required: true, message: '请设置消耗时间', trigger: 'blur' }],
        imageUrl: [{ required: true, message: '请上传图片', trigger: 'blur' }],
        consumptionQuantity: [{ required: true, message: '请输入消耗量', trigger: 'blur' }]
      }
    };
  },
  async created() {
    await Promise.all([
      this.getList(),
      this.getMaterialList()
    ])
  },
  methods: {
    async getMaterialList() {
      const { code, data, msg } = await queryMaterialList({ name: '' })
      if (code !== 200) return this.$message.error(msg);
      this.materialList = data
    },
    handleSubmit() {
      this.$refs['addForm'].validate(async (valid) => {
        if (!valid) return;
        // 判断库存
        if (this.material.remainingQuantity < this.addForm.consumptionQuantity) {
          return this.$message.error('库存不足')
        }
        // 库存预警判断
        if (this.material.inventoryThreshold >= this.addForm.consumptionQuantity) {
          this.$message.error('库存预警')
        }
        const { code, msg } = await createConsume({
          ...this.addForm,
          createUserId: this.userId,
          createUserName: this.name
        })
        if (code !== 200) return this.$message.error(msg);
        this.$message.success('添加成功')
        this.closeAddForm()
        return this.getList();
      })
    },
    resetFields () {
      Object.assign(this.$data.addForm, this.$options.data().addForm)
    },
    showAddForm() {
      this.resetFields()
      this.dialogVisible = true
    },
    closeAddForm() {
      this.editId = ''
      this.dialogVisible = false;
      this.editDisabled = false;
      this.resetFields();
    },
    handleFileSuccess({ code, data }, file) {
      if (code !== 200) return;
      const isImage = ["png", "jpg", "jpeg"].some(v => file.raw.type.includes(v))
      if (!isImage) return;
      this.addForm.imageUrl = data.url
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    },
    indexMethod(index) {
      return index + 1;
    },
    handleDetail (recode) {
      this.editDisabled = true
      this.editId = recode.id
      this.addForm = pick(recode, Object.keys(this.addForm))
      this.dialogVisible = true
    },
    /** 查询订单表列表 */
    async getList() {
      if (this.queryParams.Time) {
        this.queryParams.startTime = this.queryParams.Time[0]
        this.queryParams.endTime = this.queryParams.Time[1]
      }
      const { code, rows, total, msg } = await queryStockList(omit(this.queryParams, 'Time'))
      if (code !== 200) return this.$message.error(msg);
      this.orderList = rows;
      this.total = +total;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      Object.assign(this.$data.queryParams, this.$options.data().queryParams)
      this.handleQuery();
    },

    // 时间搜索条件change方法
    handleChange(value) {
      if (!value) {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
    }
  }
};
</script>
<style lang="scss">
.product-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 340px;

  .product-item {
    margin: auto;
    width: 290px;

    .sp-data {
      font-size: 13px;
    }

    .quantity {
      font-weight: bold;
      font-size: 13px;
    }
  }
}

.note-title {
  font-weight: bold;
}

.el-table .my-cell {
  vertical-align: top
}

.el-link.el-link--default {
  color: #409eff;
}

.el-select {
  width: 100%;
}
.file-uploader {
  width: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #409EFF;
    i {
      color: #409EFF;
    }
  }

  .file-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .file {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
